package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ApLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    private CacheService cacheService;

    /**
     * 点赞或取消点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeBehavior(ApLikesBehaviorDto dto) {
        //1.校验参数
        if(dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取用户id
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.将数据存入redis中
        //判断是点赞还是取消点赞
        if(dto.getOperation() == 0){
            //先看redis中是否有该用户点赞当前文章的信息
            Object obj = cacheService.hGet("like_" + dto.getArticleId()+"_"+dto.getType(), AppThreadLocalUtil.getUser().getId().toString());
            if(obj == null){
                //该用户没有点过赞,添加到redis中
                cacheService.hPut("like_" + dto.getArticleId(), AppThreadLocalUtil.getUser().getId().toString(),JSON.toJSONString(dto));
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }else {
                //已经点过赞
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        }else if(dto.getOperation() == 1){
            //取消点赞
            cacheService.hDelete("like_" + dto.getArticleId(), AppThreadLocalUtil.getUser().getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
